Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Vector → Vector in Java

Vector

Vector in Java

Vector: A Legacy Thread-Safe Dynamic Array

Vector is a class that implements the List interface in Java. It provides functionality similar to ArrayList, but with a key difference: Vector offers thread-safety. However, due to its thread-safety mechanisms and some limitations, it's generally considered a legacy class in modern Java development.

Key Points about Vector

Thread-Safety: Vector methods are synchronized, making them safe for access from multiple threads concurrently. This was particularly important in earlier versions of Java with less robust concurrency support. Dynamic Array: Similar to ArrayList, Vector allows dynamic resizing as elements are added or removed. It maintains an internal capacity and automatically increases it when needed. Legacy Class: While Vector was a core collection class in earlier Java versions, it's generally recommended to use ArrayList or other more modern collections for most cases. ArrayList offers better performance for single-threaded access, and for multithreaded scenarios, consider CopyOnWriteArrayList which provides a good balance between mutability and thread-safety. Synchronization Overhead: The synchronized methods in Vector can introduce some overhead compared to non-synchronized collections like ArrayList.

Declaring a Vector

Similar to LinkedList and ArrayList, declaring a Vector involves creating a reference variable of the Vector class. This variable will hold the reference to the actual Vector object you create. Here's the syntax:
Vector declaration syntaxVector<DataType> vectorName;
Explanation : Vector: This specifies the class you're using to create the collection. <DataType>: This is a placeholder for the actual data type the Vector will store (e.g., String, Integer, etc.). Replace it with the desired data type for your elements. vectorName: This is the name you choose for your reference variable. It can be any valid identifier.

Initializing a Vector

There are three main ways to initialize a Vector in Java. 1. Creating an empty Vector
Creating an empty vectorVector<String> names = new Vector<>();
Explanation : You use new Vector<>() to create a new, empty Vector object. The angle brackets <> specify the data type the Vector will hold (String in this case). You assign this object to the reference variable names. Now, names points to an empty Vector.
2. Creating a Vector with initial elements (Collection initializer)
Creating a Vector with elements Vector numbers = new Vector<>() {{ add(10); add(20); add(30); }};
Explanation : This approach is similar to LinkedList initialization using a collection initializer: You use a collection initializer within the Vector constructor. This allows you to directly add elements ("10", "20", "30") during creation. The code inside the curly braces {} defines the initial elements to be added.
3. Creating a Vector with initial capacity and capacity increment (deprecated)
Creating a Vector with initial capacity and capacity increment(deprecated) // This approach is deprecated in modern Java due to potential performance issues Vector<String> fruits = new Vector<>(5, 3);
Explanation : You specify an initial capacity (5) for the underlying array within the Vector. This can improve performance if you expect to add a significant number of elements. You can optionally specify a capacity increment (3) which determines how much the internal array grows when it's full. Important Note: The third approach using initial capacity and capacity increment is considered deprecated in modern Java due to potential performance issues. It's generally recommended to use the first two approaches for creating Vectors.
Here are examples of Vectors containing elements of various data types in Java:

1. Integers

Vector example in java collections import java.util.Vector; public class Main { public static void main(String[] args) { Vector<Integer> numbers = new Vector<>(); numbers.add(10); numbers.add(20); numbers.add(35); System.out.println(numbers.get(0)); for (int number : numbers) { System.out.println(number); } } }

Output

10 10 20 35

Explanation : This code creates a Vector named numbers that stores integer values. It then iterates through the Vector and prints each element.

2. Strings

Vector example with strings in java collections import java.util.Vector; public class Main { public static void main(String[] args) { Vector<String> names = new Vector<>(); names.add("Alice"); names.add("Bob"); names.add("Charlie"); System.out.println(numbers.get(0)); for (String name : names) { System.out.println(name); } } }

Output

Alice Alice Bob Charlie

Explanation : This code creates a Vector named names that stores string values representing names. It iterates through the Vector and prints each name.

3. Doubles

Vector example with double in java collections import java.util.Vector; public class Main { public static void main(String[] args) { Vector<Double> prices = new Vector<>(); prices.add(19.99); prices.add(24.50); prices.add(12.75); System.out.println(prices.get(0)); for (double price : prices) { System.out.println(price); } } }

Output

19.99 19.99 24.5 12.75
Explanation : This code creates a Vector named prices that stores double values representing prices. It iterates through the Vector and prints each price.

4. Characters

Vector examples with charcters in java collections import java.util.Vector; public class Main { public static void main(String[] args) { Vector<Character> initials = new Vector<>(); initials.add('A'); initials.add('B'); initials.add('C'); System.out.println(initials.get(0)); for (char initial : initials) { System.out.println(initial); } } }

Output

A A B C
Explanation : This code creates a Vector named initials that stores character values representing initials. It iterates through the Vector and prints each character.

5. Custom Objects

Vector with objects in java collections import java.util.Vector; class Product { int id; String name; double price; public Product(int id, String name, double price) { this.id = id; this.name = name; this.price = price; } } public class Main { public static void main(String[] args) { Vector<Product> products = new Vector<>(); products.add(new Product(1, "Laptop", 599.99)); products.add(new Product(2, "Headphones", 79.95)); products.add(new Product(3, "Monitor", 199.99)); System.out.println(products.get(1).name); for (Product product : products) { System.out.println("ID: " + product.id + ", Name: " + product.name + ", Price: $" + product.price); } } }

Output

Headphones ID: 1, Name: Laptop, Price: $599.99 ID: 2, Name: Headphones, Price: $79.95 ID: 3, Name: Monitor, Price: $199.99
Explanation : This code defines a custom class Product with attributes like id, name, and price. It then creates a Vector named products that stores instances of the Product class. The code iterates through the Vector and prints details of each product.
Remember, Vector can hold elements of any data type as long as you declare the appropriate type parameter within the angle brackets < > when creating the Vector. While Vector offers functionality similar to ArrayList, it's generally less preferred in modern Java due to its thread-safety features which can impact performance. Use Vector only if thread-safety is a critical requirement in your application. Important Considerations: In most modern Java development, ArrayList is the preferred choice for dynamic arrays due to its performance benefits for single-threaded access. For thread-safe scenarios, consider CopyOnWriteArrayList which provides a more efficient approach to thread-safety for mutable lists. If you encounter Vector in legacy code, understand its purpose and potential limitations compared to modern collection options. In Conclusion: While Vector has historical significance in Java collections, its thread-safety features come with some performance overhead. For most modern Java development, ArrayList or CopyOnWriteArrayList are better suited choices depending on your specific needs for mutability and thread-safety.

Tutorials